package com.zr.redis.util;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class WatchDogLockUtil {

    private final RedissonClient redissonClient;

    // 看门狗默认过期时间（30秒），可通过配置文件修改
    @Autowired
    public WatchDogLockUtil(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 使用看门狗模式获取锁（不指定过期时间）
     * @param lockKey 锁的键
     * @return 锁对象
     */
    public RLock lockWithWatchDog(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        // 不指定过期时间，自动启用看门狗
        lock.lock();
        return lock;
    }

    /**
     * 尝试使用看门狗模式获取锁
     * @param lockKey 锁的键
     * @param waitTime 最大等待时间
     * @param unit 时间单位
     * @return 是否获取成功
     * @throws InterruptedException 中断异常
     */
    public boolean tryLockWithWatchDog(String lockKey, long waitTime, TimeUnit unit) throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        // 不指定过期时间，自动启用看门狗
        return lock.tryLock(waitTime, -1, unit);
    }

    /**
     * 释放锁
     * @param lock 锁对象
     */
    public void unlock(RLock lock) {
        if (lock != null && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    /**
     * 释放锁
     * @param lockKey 锁的键
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

